package com.xindaoapp.happypet.activity;

import java.util.LinkedList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.MyHuiFu;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class SearchResultActivity extends UMBaseActivity implements OnClickListener {
    private String str;
    @ViewInject(R.id.tittle_myattention_cancel)
    private ImageButton tittle_myattention_cancel;
    @ViewInject(R.id.tittle_myattention_ok)
    private ImageButton tittle_myattention_ok;
    @ViewInject(R.id.loading)
    private FrameLayout loading;
    @ViewInject(R.id.tittle_myattention_content)
    private TextView tittle_myattention_content;

    /** 初始化我帖子信息详情 */

    private MyHuiFuAdapter adapter;
    @ViewInject(R.id.myhuifu_list)
    private PullToRefreshListView myhuifu_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myhuifu);
        ViewUtils.inject(this);
        initClick();
        tittle_myattention_ok.setVisibility(View.GONE);
        // myhuifu_list.setPullLoadEnabled(true);
        // myhuifu_list.setPullLoadEnabled(true);
        initListView();

        loading.setVisibility(View.VISIBLE);
        loadData(1);
        // setLastUpdateTime();
    }

    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        myhuifu_list.setLastUpdatedLabel(text);
    }

    private int currentpage = 0;

    private void initListView() {
        str = getIntent().getStringExtra("str");
        // myhuifu_list.setPullLoadEnabled(true);
        myhuifu_list.setPullRefreshEnabled(false);
        myhuifu_list.setScrollLoadEnabled(true);
        myhuifu_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // loadData(currentpage++);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                loadData(currentpage++);

            }
        });
        setLastUpdateTime();
    }

    private void initClick() {
        tittle_myattention_content.setText("搜索结果");
        tittle_myattention_content.setTextColor(Color.WHITE);
        tittle_myattention_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_myattention_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    private final LinkedList<Message> arrays = new LinkedList<Message>();

    private void loadData(int currentPage) {
        RequestParams params = new RequestParams();
        params.put("word", str);
        params.put("page", String.valueOf(currentPage));
        params.put("pagesize", "10");
        XDHttpClient.get(xdConfig.SEARCH, params, new AsyncHttpResponseHandler() {
            private List<Message> array;

            @Override
            public void onSuccess(int statusCode, String content) {
                if (loading.getVisibility() == View.VISIBLE) {
                    loading.setVisibility(View.GONE);
                }
                MyHuiFu huifu = JSON.parseObject(content, MyHuiFu.class);
                array = huifu.getArray();
                if (array.size() == 0) {
                    Toast.makeText(SearchResultActivity.this, "搜索结果为空,请返回重新搜索", Toast.LENGTH_SHORT)
                            .show();
                    myhuifu_list.setPullLoadEnabled(false);
                    myhuifu_list.setPullRefreshEnabled(false);
                    return;
                }

                arrays.addAll(array);
                if (adapter == null) {
                    adapter = new MyHuiFuAdapter();
                    myhuifu_list.getRefreshableView().setAdapter(adapter);
                } else {
                    adapter.notifyDataSetChanged();
                }
                if (huifu.getTotal().equals(arrays.size())) {
                    myhuifu_list.setHasMoreData(false);
                    myhuifu_list.setPullLoadEnabled(false);
                    myhuifu_list.setPullRefreshEnabled(false);
                    Toast.makeText(getApplicationContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                    onLoaded();
                }
                super.onSuccess(statusCode, content);
                onLoaded();
            }

            @Override
            public void onFailure(Throwable error, String content) {
                Toast.makeText(getApplicationContext(), "正在努力加载", Toast.LENGTH_SHORT).show();
                super.onFailure(error, content);
                onLoaded();
            }
        });
    }

    private void onLoaded() {
        myhuifu_list.onPullDownRefreshComplete();
        myhuifu_list.onPullUpRefreshComplete();
    }

    private class MyHuiFuAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return arrays.size();
        }

        @Override
        public Object getItem(int position) {
            return arrays.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView =
                        View.inflate(SearchResultActivity.this, R.layout.message_list_item, null);
                holder = new ViewHolder();
                holder.usertouxiang =
                        (CircleImageView) convertView
                                .findViewById(R.id.message_list_item_usertouxiang);
                holder.messagetittle =
                        (TextView) convertView.findViewById(R.id.message_list_item_messagetittle);
                holder.username =
                        (TextView) convertView.findViewById(R.id.message_list_item_username);
                holder.looktime =
                        (TextView) convertView.findViewById(R.id.message_list_item_looktime);
                holder.caretime =
                        (TextView) convertView.findViewById(R.id.message_list_item_caretime);
                holder.huifutime =
                        (TextView) convertView.findViewById(R.id.message_list_item_huifutime);
                holder.time = (TextView) convertView.findViewById(R.id.message_list_item_time);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.messagetittle.setText(arrays.get(position).subject);
            holder.username.setText(arrays.get(position).author);
            holder.looktime.setText(arrays.get(position).views);
            holder.caretime.setText(arrays.get(position).recommend_add);
            holder.huifutime.setText(arrays.get(position).replies);
            String time = CommonUtil.formatDate();
            if (arrays.get(position).addtime.split(" ")[0].equals(time.split(" ")[0])) {// 说明是今天
                String today = arrays.get(position).addtime.split(" ")[1];
                holder.time.setText(today.substring(0, 5));
            } else {
                holder.time.setText(arrays.get(position).addtime.split(" ")[0].substring(5, 10));
            }
            holder.usertouxiang.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(arrays.get(position).userface,
                    holder.usertouxiang);
            adapter.notifyDataSetChanged();
            return convertView;
        }
    }

    public class ViewHolder {
        CircleImageView usertouxiang;
        TextView messagetittle;
        TextView username;
        TextView looktime;
        TextView caretime;
        TextView huifutime;
        TextView time;
    }

    /** 设置加载的时间 */
    // private void setLastUpdateTime() {
    // String text = CommonUtil.getStringDate();
    // myhuifu_list.setLastUpdatedLabel(text);
    // }
    //
    // /**
    // * 结束上拉和下拉刷新
    // */
    // private void onLoaded() {
    // myhuifu_list.onPullDownRefreshComplete();
    // myhuifu_list.onPullUpRefreshComplete();
    // }
}
